package com.ruoyi.stock2.thread;

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.stock2.domain.STOCK;
import com.ruoyi.stock2.domain.TRADEDATA;
import com.ruoyi.stock2.service.ISTOCKService;
import com.ruoyi.stock2.service.ITRADEDATAService;
import com.ruoyi.stock2.utils.DateUtils2;

import java.io.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

//生成训练集以行业分组 时间比较长
public class BuildSeq2SeqTrainTextGroupByIndustryThread implements Runnable {

    ITRADEDATAService itradedataService;

    ISTOCKService istockService;

    private boolean working = false;

    public boolean isWorking() {
        return working;
    }

    public void setWorking(boolean working) {
        this.working = working;
    }

    //单例实现 涉及到任务状态
    public static BuildSeq2SeqTrainTextGroupByIndustryThread getInstance() {
        return Singtonle.instance;
    }

    private static class Singtonle {
        private static BuildSeq2SeqTrainTextGroupByIndustryThread instance = new BuildSeq2SeqTrainTextGroupByIndustryThread();
    }

    private String industry;

    public void setIndustry(String industry) {
        this.industry = industry;
    }

    public String getIndustry() {
        return industry;
    }

    @Override
    public void run() {
        working = true;
        itradedataService = (ITRADEDATAService) SpringUtils.getBean(ITRADEDATAService.class);
        istockService = (ISTOCKService) SpringUtils.getBean(ISTOCKService.class);
        buildTrainToTxt(industry);
        working = false;
    }
    public String getLocalDateStr(Date date, String formatter) {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);

        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
        String dateStr = dateTimeFormatter.format(localDateTime);

        return dateStr;
    }

    public void buildTrainToTxt(String industry) {
        STOCK stocksearch = new STOCK();
        stocksearch.setIndustry(industry);
        List<STOCK> list = istockService.selectSTOCKList(stocksearch);
        File file = new File("f:/seq2seq_train_text/" + industry + ".txt");
        BufferedWriter writer = null;

        try {
            if(!file.exists()){
                file.createNewFile();
            }else{
                file.delete();
                file.createNewFile();
            }

            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "utf-8"));
            writer.write( "SYMBOL,NAME,DATETIME,CLOSEPRICE,ZHANGFU\r\n");

            for (STOCK stock : list) {
                TRADEDATA tradedata = new TRADEDATA();
                tradedata.setSymbol(stock.getSymbol());
                //小于2020-04-06
                tradedata.setDatetime(DateUtils2.formatStringToDate("2020-04-06", "yyyy-MM-dd"));
                List<TRADEDATA> listtrades = itradedataService.selectTradedataListForSeq2SeqTrainData(tradedata);

                for (int i = 0; i < listtrades.size(); i++) {
                    TRADEDATA tradedata1 = listtrades.get(i);
                    String dateTimeString = getLocalDateStr(tradedata1.getDatetime(),"yyyy-MM-dd");
                    String sb = tradedata1.getSymbol() + "," + stock.getName() + "," + dateTimeString + "," + tradedata1.getCloseprice() + "," + tradedata1.getZhangfu();
                    if (sb != null) {
                        writer.write(sb + "\r\n");
                    }
                }
                writer.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



        System.out.println("完成");
    }


    /**
     * 执行命令
     * @param cmd
     * @throws IOException
     */
    public void exec(String cmd) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();
        System.out.println("开始执行shell命令," + cmd);
        Process process = Runtime.getRuntime().exec(cmd);
        printMessage(process.getInputStream());
        printMessage(process.getErrorStream());
        if (process.waitFor()==0){
            System.out.println("命令执行成功(总耗时:"+(System.currentTimeMillis()-startTime)/1000+"秒)");
        }else {
            System.err.println("命令执行成功失败");
        }
    }

    /**
     * 读取流到控制台(防止死锁)
     * @param input
     */
    private void printMessage(final InputStream input) {
        new Thread(new Runnable(){
            @Override
            public void run() {
                Reader reader = new InputStreamReader(input);
                BufferedReader bf = new BufferedReader(reader);
                String line = null;
                try{
                    while((line=bf.readLine())!=null){
                        System.out.println(line);
                    }
                }
                catch(IOException e){
                    e.printStackTrace();
                }finally {
                    try {
                        input.close();
                    } catch (IOException e) {}
                }

            }}).start();

    }

}
